<?php
/**
 * 个人网址文件夹
 */
namespace APP\M;

class Url extends Model
{
    const T_URL = 'user_url';
    const T_BASE = 'user_url_base';

    public function init()
    {
        if (!$this->_email) {
            throw new Exception("文件夹操作：用户标识丢失");
        }
    }

    /**
     * 获取列表
     */
    public function getList($page, $num, $cid = 0)
    {
        $page >= 1 || $page = 1;
        $limit = ($page - 1) * $num;
        //$where = $cid ? ' AND ucid='. $cid : '';
        $where = ' AND ucid='. $cid;
        $sql = 'SELECT SQL_CALC_FOUND_ROWS id, ucid, ubid, title, url, intro, DATE(create_tm) as create_tm FROM '. self::T_URL .' WHERE email="'. $this->_email .'"'. $where .' ORDER BY id DESC LIMIT '. $limit .', '. $num;
        return $this->getDb()->fetchAll($sql);
    }


    /**
     * 保存url
     */
    public function save($data)
    {
        // 保存前先处理一下url
        $data['url'] = $this->assembleUrl($data['url']);
        $data['ubid'] = $this->parseUrl($data['url']);


        // 保存
        $o_ucid = 0;
        if (isset($data['id']) && $this->isUrlExists($data['id'])) {
            // 原来的分类id
            $sql = 'SELECT ucid FROM '. self::T_URL .' WHERE id='. $data['id'];
            $o_ucid = $this->getDb()->fetchOne($sql);
            $this->getDb()->update(self::T_URL, $data, array('id=?'=>$data['id']));
            $id = $data['id'];
        } else {
            unset($data['id']);
            $data['email'] = $this->_email;
            $data['create_tm'] = date('Y-m-d H:i:s', $this->getTimestamp());
            $this->getDb()->insert(self::T_URL, $data);
            $id = $this->getDb()->fetchOne('SELECT last_insert_id()');

            // 修改分类的统计数
            $this->getModel('cata')->upCount($data['ucid'], $o_ucid);
            $this->getModel('user')->upFavCount();
        }
        return $id;
    }


    /**
     * 修改简介
     */
    public function saveIntro($id, $intro)
    {
        $sql = 'UPDATE '. self::T_URL .' SET intro="'. $intro .'" WHERE id='. (int)$id;
        $this->getDb()->query($sql);
    }


    /**
     * 处理成完整的url
     */
    public function assembleUrl($url)
    {
        if (strpos($url, '://') === false) {
            $url = 'http://'. $url;
        }
        return $url;
    }

    /**
     * 从链接获取域名
     * 处理域名信息，入库
     * @return 对应的ubid
     */
    public function parseUrl($url)
    {
        $urlInfo = parse_url($url);
        isset($urlInfo['scheme']) || $urlInfo['scheme'] = 'http';
        if (!isset($urlInfo['host'])) {
            return 0;
        }
        $sub = $urlInfo['host'];
        $top = preg_replace('/([\w-.]+\.)?([\w\-]+)\.([\w\-]+)/i', '\2.\3', $sub);
        $sql = 'SELECT id FROM '. self::T_BASE .' WHERE top="'. $top .'" AND sub="'. $sub .'"';
        if (true != ($id = $this->getDb()->fetchOne($sql))) {
            $this->getDb()->insert(self::T_BASE, array(
                'scheme' => $urlInfo['scheme'],
                'top' => $top,
                'sub' => $sub
            ));
            $id = $this->getDb()->fetchOne('SELECT last_insert_id()');
        }
        return $id;
    }


    /**
     * 获取某个用户下的收藏总数
     */
    public function getCount($by = 'email', $val = '')
    {
        if ($by == 'email' && $val == '') {
            $val = $this->_email;
        }
        $sql = 'SELECT COUNT(*) FROM '. self::T_URL .' WHERE `'. $by .'`="'. $val .'"';
        return $this->getDb()->fetchOne($sql);
    }

    /**
     * 删除某分类下所有网址
     */
    public function deleteByCid($cid)
    {
        $this->getDb()->delete(self::T_URL, array('ucid=?'=>$cid, 'email=?'=>$this->_email));
        $this->getModel('user')->upFavCount();
    }

    /**
     * 删除某条网址
     */
    public function deleteById($id)
    {
        $this->getDb()->delete(self::T_URL, array('id=?'=>$id, 'email=?'=>$this->_email));
        $this->getModel('user')->upFavCount();
    }


    /**
     * 是否存在，按id或按name判断
     */
    public function isUrlExists($id)
    {
        $sql = 'SELECT COUNT(*) FROM '. self::T_URL .' WHERE id='. $id;
        return $this->getDb()->fetchOne($sql);
    }
}